<template>
  <div class="online-process-detail content bg-white full-height">
    <template>
      <div class="q-pa-md">
        <div class="row title-box">
          <div class="col-lg-3  col-sm-6 font-size-16">在产：<span class="font-size-14">{{data.productName}}<q-tooltip>{{data.productName}}</q-tooltip></span></div>
          <div class="col-lg-3  col-sm-6 font-size-16">工序：<span class="font-size-14">{{data.processPlanningName}}<q-tooltip>{{data.processPlanningName}}</q-tooltip></span></div>
          <div class="col-lg-3  col-sm-6 font-size-16">设备：<span class="font-size-14">{{data.deviceName}}<q-tooltip>{{data.deviceName}}</q-tooltip></span></div>
          <div class="col-lg-3  col-sm-6 font-size-16 equipment-name">
            所在位置：<span class="font-size-14">{{data.workshopName || '--'}}<q-tooltip>{{data.workshopName || '--'}}</q-tooltip></span>
          </div>
        </div>
      </div>
    </template>
    <template>
      <div class="q-pa-md">
        <q-table
          table-class="procedure-table"
          :data="programs"
          :columns="programColumns"
          row-key="name"
          no-data-label="暂无数据"
          hide-bottom
        >
          <template v-slot:header="props">
            <q-tr :props="props">
              <q-th
                v-for="col in props.cols"
                :key="col.name"
                :props="props"
                class="bor-t bor-b"
              >
                {{ col.label }}
              </q-th>
            </q-tr>
          </template>
          <template v-slot:body="props">
            <q-tr :props="props">
              <q-td key="programName" :props="props" class="bor-b" :class="{ on: props.row.isCurrentExecute}">
                {{ props.row.programName}}
              </q-td>
              <q-td key="programSize" :props="props" class="bor-b" :class="{ on: props.row.isCurrentExecute}">
                {{props.row.programSize}}K
              </q-td>
            </q-tr>
          </template>
        </q-table>
      </div>
    </template>
    <template>
      <div class="q-pa-md">
        <q-table
          table-class="row-table"
          :data="commandsData"
          :columns="rowColumns"
          row-key="name"
          no-data-label="暂无数据"
          hide-bottom
        >
          <template v-slot:header="props">
            <q-tr :props="props">
              <q-th
                v-for="col in props.cols"
                :key="col.name"
                :props="props"
                class="bor-t bor-b"
              >
                {{ col.name === 'commands' ? `${currentCommand}/${commandCount}`:col.label }}
              </q-th>
            </q-tr>
          </template>
          <template v-slot:body="props">
            <q-tr :props="props">
              <q-td key="row" :props="props" class="row-num bor-b ">
                {{ props.row.row}}
              </q-td>
              <q-td key="commands" :props="props" class="bor-b">
                {{ props.row.commands}}
              </q-td>
            </q-tr>
          </template>
        </q-table>
      </div>
    </template>
  </div>
</template>

<script>
import { getDetailed } from 'src/boot/program/online'
import refreshMixin from '../../assets/js/refresh-mixin'
import { mapGetters } from 'vuex'
import _ from 'lodash'

export default {
  name: 'online-process-detail',
  mixins: [refreshMixin],
  computed: {
    ...mapGetters([
      'userInfo'
    ])
  },
  data () {
    return {
      // pagination: {
      //   rowsPerPage: 0
      // },
      visibleColumns: ['programName', 'programSize'], // 工序表显示字段
      programColumns: [
        { name: 'programName', label: '程序名称', align: 'left', field: 'programName' },
        { name: 'programSize', label: '文件大小', align: 'left', field: 'programSize' },
        { name: 'isrowExecute', label: '', align: 'left', field: 'isrowExecute' }
      ], // 工序表头
      programs: [], // 工序表数据
      schemeLevelName: '', // 计划名
      rowColumns: [
        { name: 'row', label: '当前执行:', align: 'center', field: 'row' },
        { name: 'commands', label: '4/200', align: 'left', field: 'commands' }
      ], // 当前执行表头
      data: {},
      //  mqtt实例
      client: null,
      // 查询定时器
      timerGetDetail: null,
      timerTime: null,
      commandCount: '', // 总行数
      currentCommand: '--', // 当前行数
      commandsData: [] // 当前执行表数据
    }
  },
  mounted () {
    // 每60秒重新订阅一次mqtt防止订阅失效
    // this.timerMqtt = setInterval(this.onConnect, 60000)
    // 每3分钟重新查询列表以更新应完成产量
    this.timerGetDetail = setInterval(this.getListData, 300000)
    this.timerTime = setInterval(this.sendMsg, 60000)
  },
  beforeDestroy () {
    // 清除定时器
    clearInterval(this.timerGetDetail)
    clearInterval(this.timerTime)
    // 取消订阅
    this.closeUbscribeTopic()
    // 关闭连接
    this.client.disconnect()
  },
  beforeRouteUpdate () {
    // 取消订阅
    this.closeUbscribeTopic()
    // 关闭连接
    this.client.disconnect()
  },
  watch: {
    '$route' (to, from) {
      if (to.name === 'online-process-detail') {
        this.init(to.query)
      }
    }
  },
  methods: {
    /**
     * 全局刷新数据
     * author: xueli
     */
    refreshInfo () {
      this.init(this.$route.query)
    },
    init (query) {
      this.data = query
      this.getProcessingDetail()
      // 初始化mqtt
      this.initMqtt()
    },
    /**
     * 初始化mqtt
     */
    initMqtt () {
      console.log(this.CommonConfig.mqttConfig.MQTT_SERVICE)
      // 生成一个唯一的userId用于连接盒子，此id必须唯一
      const userId = 'webClient' + this.userInfo.user_id.toString() + Date.parse(new Date()).toString()
      // 创建mq实例
      this.client = new window.Paho.MQTT.Client(
        this.CommonConfig.mqttConfig.MQTT_SERVICE,
        Number(this.CommonConfig.mqttConfig.MQRR_PORT),
        userId)
      // 连接服务器并注册连接成功处理事件
      this.client.connect({ onSuccess: this.onConnect })
      // 注册连接断开处理事件
      this.client.onConnectionLost = this.onConnectionLost
      // 注册消息接收处理事件
      this.client.onMessageArrived = this.onMessageArrived
    },
    /**
     * 接受盒子返回消息
     * @param {string} message
     */
    onMessageArrived (message) {
      // 分割topic
      let msgBoxIds = message.destinationName.split('/')

      let msgBoxId = msgBoxIds[4]
      if (msgBoxIds[3] === 'DNC') {
        let msg = _.split(message.payloadString, '|')
        this.currentCommand = msg[2]
        if (this.commandsData.length === 3) {
          this.commandsData = _.drop(this.commandsData)
        }
        this.commandsData.push({
          row: msg[2],
          commands: msg[1]
        })
      } else {
        let msg = JSON.parse(message.payloadString)

        console.log(msg, msgBoxId, '序列化的消息')
        // runType为1时，切换当前程序
        if (msg.runType) {
          this.getProcessingDetail()
          // this.commandCount = msg.count
          this.currentCommand = '--'
          this.commandsData = []
          // const currentExecuteIndex = this.programs.filter(item => item.isCurrentExecute)[0].index
          // this.programs[currentExecuteIndex].isCurrentExecute = false
          // this.programs[currentExecuteIndex + 1].isCurrentExecute = true
          // console.log(currentExecuteIndex)
        }
      }
    },
    /**
     * 订阅并发送消息
     */
    onConnect () {
      console.log('连接成功')
      this.client.subscribe(
        `${this.CommonConfig.mqttConfig.MQTT_TOPIC.onlineProcessDetail.subscribeTopic}${this.data.boxId}`, { qos: 1 }
      )// 订阅主题
      this.client.subscribe(
        `${this.CommonConfig.mqttConfig.MQTT_TOPIC.programName.subscribeTopic}${this.data.boxId}`, { qos: 1 }
      )// 订阅主题（程序名称）
    },
    // 发送消息
    sendMsg () {
      this.onSend(
        this.CommonConfig.mqttConfig.MQTT_TOPIC.onlineProcessDetail.sendTopic,
        this.data.boxId,
        this.CommonConfig.mqttConfig.MQTT_TOPIC.onlineProcessDetail.type
      )
    },
    // 发送消息(type为qos类型)
    onSend (sendTopic, boxId, type) {
      let message = new window.Paho.MQTT.Message(type)
      const topic = `${sendTopic}${boxId}`.toString()
      message.destinationName = topic
      this.client.send(message)
    },
    /**
     * 取消订阅
     */
    closeUbscribeTopic () {
      console.log('断开')
      this.client.unsubscribe(`${this.CommonConfig.mqttConfig.MQTT_TOPIC.onlineProcessDetail.subscribeTopic}${this.data.boxId}`)
      this.client.unsubscribe(`${this.CommonConfig.mqttConfig.MQTT_TOPIC.programName.subscribeTopic}${this.data.boxId}`)
    },
    /**
     * 连接丢失
     * @param {{}} responseObject
     */
    onConnectionLost (responseObject) {
      console.log('在线加工详情，连接断开事件', responseObject)
      if (responseObject.errorCode !== 0) {
        this.onConnect()
        console.log('onConnectionLost:' + responseObject.errorMessage)
        console.log('连接已断开')
      }
    },
    // 获取详情
    getProcessingDetail () {
      getDetailed(this.data.deviceId).then(res => {
        res.data.programs.forEach((item, index) => {
          item.index = index
        })
        this.programs = res.data.programs
        this.schemeLevelName = res.data.schemeLevelName
        this.commandCount = res.data.commandCount
        this.data.productName = `${res.data.productName || '--'}(${res.data.productNumber || '--'})`
        this.data.processPlanningName = `${res.data.processPlanningSort + 1}-${res.data.processPlanningName || '--'}`
        this.data.workshopName = res.data.workshopName
      })
    }
  },
  created () {
    this.init(this.$route.query)
  }
}
</script>

<style scoped lang="stylus">
  .font-size-16 {
    font-size 16px
  }
  .font-size-14 {
    font-size 14px
  }
  .title-box{
    padding 7px 30px
    border-top #D3D3D3 1px solid
    border-bottom #D3D3D3 1px solid
  }
  .equipment-name{
    overflow: hidden;
    text-overflow:ellipsis;
    white-space: nowrap;
  }
  .max-h{
    max-height calc(40%);
  }
  td .item{
    margin-left 10px
  }
  td .item:first-child{
    margin-left 0
  }
  .row-table tr:last-child td{
    background-color rgba(95,119,253,.2)
  }
  .row-num{
    width 100px
    border-right #D3D3D3 1px solid
  }
  .bor-t{
    border-top #D3D3D3 1px solid
  }
  .bor-b{
    border-bottom #D3D3D3 1px solid
  }
  .bor-b.on{
    background-color rgba(95,119,253,.2)
  }
</style>
